<template>
    <div class="container">
        <!-- 导航栏区域开始 -->
        <TridentNavBar>
            <template #left><i class="icon iconfont icon-zuojiantou"></i></template>
            <template #default>修改地区</template>
            <template #right><i class="icon iconfont icon-wode" @click="$router.push({path: '/me'})"></i></template>
        </TridentNavBar>
        <!-- 导航栏区域结束 -->

        <van-form @submit="handleSave">
            <van-field
                v-model="formData.region"
                is-link
                readonly
                label="地区选择"
                left-icon="location-o"
                placeholder="请选择所在地区"
                @click="handleShowArea"
            />

            <!-- 地区弹层区域开始 -->
            <van-popup v-model:show="showArea" round position="bottom">
                <van-cascader
                    v-model="cascaderValue"
                    title="请选择所在地区"
                    :options="areaList"
                    active-color="#27BA9B"
                    @close="showArea = false"
                    @finish="onFinish"
                    @change="handleChange"
                    :field-names="fieldNames"
                />
            </van-popup>
            <!-- 地区弹层区域结束 -->

            <!-- 保存按钮 -->
            <div style="margin: 16px">
                <van-button
                    type="primary"
                    native-type="submit"
                    round
                    block
                    color="#27BA9B"
                >
                    保&nbsp;&nbsp;存
                </van-button>
            </div>
		</van-form>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue"
import { showSuccessToast } from 'vant'
import { useUserStore } from '@/store/modules/user'
import { reqRegionTreeAPI } from "@/apis/common"
import type { RegionTree } from "@/types/common"
import { EditUserParams } from "@/types/user"

// 用户存储
const userStore = useUserStore()

const showArea = ref<boolean>(false)

const cascaderValue = ref<string>('')

const fieldNames = {
    text: 'name',
    value: 'id',
    children: 'children'
}

const handleShowArea = async () => {
    // 获取省数据
    await getRegionTree(0, 0)
    showArea.value = true
}

const index = ref<number>(0)
const handleChange = ({value, tabIndex}:{value:number, tabIndex: number}) => {
    index.value = tabIndex
    getRegionTree(value, tabIndex)
} 


// 全部选项选择完毕后，会触发 finish 事件
const onFinish = ({ selectedOptions }:{selectedOptions:any}) => {
    if (index.value == 2) {
        formData.region = selectedOptions.map((option: any) => option.name).join('-')
        formData.province_id = selectedOptions[0].id
        formData.city_id = selectedOptions[1].id
        formData.district_id = selectedOptions[2].id
        showArea.value = false
    }
};

// ----------------- 处理保存功能开始 -----------------
// 表单数据
const formData = reactive<EditUserParams>({
    province_id: userStore.profile.user.province_id,
    city_id: userStore.profile.user.city_id,
    district_id: userStore.profile.user.district_id,
    region: userStore.profile.user.region,
})

// 保存数据
const handleSave = async () => {
    await userStore.editOtherInfo(formData)
    showSuccessToast('修改成功')
}
// ----------------- 处理保存功能结束 -----------------



// ----------------- 获取区域功能开始 -----------------
const areaList = ref<RegionTree[]>([])
const getRegionTree = async (pid: number, tabIndex: number) => {
    const result = await reqRegionTreeAPI({pid})
    const regions = result.data
    if (pid == 0) {
        areaList.value = regions
        return false
    }
    let areas:any = []
	regions.forEach((item) => {
        if (tabIndex < 1) {
            areas.push({
                id: item.id,
                name: item.name,
                children: []
            })
        } else {
            areas.push({
                id: item.id,
                name: item.name,
            })
        }
	})

    if (tabIndex == 0) {
        areaList.value.find(item => item.id == pid)!.children = areas
    } else if (tabIndex == 1) {
        areaList.value.forEach((item) => {
            if (item.children?.length > 0) {
                if (item.children.find(val => val.id == pid)) {
                    item.children.find(val => val.id == pid)!.children = areas
                }
            }
        })
    }
}
// ----------------- 获取区域功能结束 -----------------
</script>

<style scoped lang="scss">
:deep .van-tabs__wrap {
    position: relative;
    z-index: 100;
    width: 100%;
}

.container {
    height: 100vh;
    background-color: ghostwhite;
	padding: 50px 5px 0 5px;
	font-size: 14px;
	line-height: 24px;
	button {
		background: #27BA9B;
	}
}
</style>